package day06;

import work.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class shiwu {
    public static void main(String[] args) throws SQLException {
        Connection conn=null;
        PreparedStatement prs=null;
        try {
            conn= JDBCUtils.getConnection();
            //手动管理事务，默认是true自动管理事务
            conn.setAutoCommit(false);
            prs=conn.prepareStatement("update account set money=money-100 where name=?");
            prs.setString(1,"a");
            prs.executeUpdate();
            //模拟出错，检测转账是否成功
//           int a=1/0;
            prs=conn.prepareStatement("update account set money=money+100 where name=?");
            prs.setString(1,"b");
            prs.executeUpdate();
            //提交事务
            conn.commit();
            System.out.println("转账成功");
        } catch (Exception e) {
            //回滚事务，将conn连接的mysql操作进行重置
            conn.rollback();
            System.out.println("转账失败");
        }
        finally {
            JDBCUtils.release(conn,prs,null);
        }
    }
}
